package com.quan.common.utils.seqnum;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.quan.common.base.enums.DateStyle;
import com.quan.common.utils.DateUtils;
import com.quan.common.utils.RedisOperator;

/**
 * 订单号生成工具类
 * @author yhaoquan
 *
 */
@Component
public class SerialNumberUtil {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private RedisOperator redisOperator;
	
	public static void main(String[] args) {
		String date = "2018-11-15 16:33:12" ;
		Date d1 = DateUtils.parse(date, DateStyle.YYYY_MM_DD_HH_MM_SS) ;
		System.out.println("当前日期："+date);
		System.out.println("当前日期毫秒："+d1.getTime());
		
		long curMin = d1.getTime() ; //当前时间毫秒
		long end24Min = DateUtils.get24HourMilliSecond() ; //当前日期的24点整
		
		System.out.println("24点：" + end24Min);
		System.out.println("24点：" + DateUtils.formatMillSecDateTime(end24Min));
		
		long residue = end24Min - curMin ; //剩余多少毫秒到24点
		System.out.println("剩余多少毫秒到24点："+residue);
		
		System.out.println(DateUtils.formatMillSecDateTime((174527 * 1000)+curMin));
	}
	
	/**
	 * 订单号生成
	 * 订单号组成【当前日期yyyyMMdd+业务编码/4位随机数+订单序列号】
	 * @param bizCode
	 * @return
	 */
	public String generateOrderNo(String bizCode) {
		String date = StringUtil.getToday(); // 时间yyMMdd
		String key = "order_seq_num";// 订单号key
		
		boolean hasKey = this.redisOperator.hasKey(key);
		
		if(!hasKey) { //key不存在
			Long time = this.redisOperator.getTime(); //获取Redis服务器时间
			this.redisOperator.incr(key); //序列号增加1
			this.redisOperator.expire(key, StringUtil.expire(time)); //设置到24点整过期
		} else {
			this.redisOperator.incr(key); //序列号增加1
		}
		
		//获取序列号
		String seq = this.redisOperator.get(key) ;
		
		//构建订单号
		StringBuffer orderNo = new StringBuffer() ;
		orderNo.append(date) ;
		orderNo.append(StringUtils.isBlank(bizCode) ? StringUtil.getRandom() : bizCode) ;
		orderNo.append(StringUtil.autoCOS(seq)) ;
		
		logger.info("订单号：{} 序列号：{} 过期时间：{}(秒)",orderNo.toString(), seq, this.redisOperator.ttl(key));
		
		return orderNo.toString() ;
	}
	
	public String generateOrderNo() {
		return generateOrderNo(null) ;
	}

}
